package com.gitee.itembucket

import com.germ.germplugin.api.dynamic.gui.GuiManager
import com.gitee.itembucket.api.event.PluginReloadEvent
import com.gitee.itembucket.core.theme.GermThemeUI
import org.bukkit.Bukkit
import org.bukkit.entity.Player
import taboolib.common.platform.ProxyCommandSender
import taboolib.common.platform.command.CommandBody
import taboolib.common.platform.command.CommandHeader
import taboolib.common.platform.command.mainCommand
import taboolib.common.platform.command.subCommand
import taboolib.common.platform.function.submit
import taboolib.common.platform.function.submitAsync
import taboolib.expansion.createHelper

@CommandHeader("itembucket", aliases = ["ib","itemb","ibucket","bucket"])
object ItemBucketCommand {

    @CommandBody
    val main = mainCommand {
        createHelper()
    }

    @CommandBody
    val log = ItemBucketLogCommand

    @CommandBody
    val open = subCommand {
        dynamic("viewer") {
            suggestion<ProxyCommandSender> { _, _ -> Bukkit.getOnlinePlayers().map { it.name } }

            dynamic("player") {
                suggestion<ProxyCommandSender> { _, _ -> Bukkit.getOnlinePlayers().map { it.name } }


                execute<ProxyCommandSender> { _, context, argument ->
                    val viewer = Bukkit.getPlayerExact(context["viewer"])!!
                    val player = Bukkit.getPlayerExact(argument)!!
                    submit(async = true) {
                        GermThemeUI(viewer, player).open()
                    }
                }

            }
        }
    }

    @CommandBody
    val reload = subCommand {
        execute<ProxyCommandSender> { sender, _, _ ->
            ItemBucket.config.reload()
            GermThemeUI.config.reload()
            ItemBucket.onEnable()
            Bukkit.getOnlinePlayers().forEach {

                if (GuiManager.isOpenedGui(it, "item-bucket")) {
                    val openedGui = GuiManager.getOpenedGui(it, "item-bucket")
                    openedGui.close()
                    val viewer = openedGui.simpleMap["@Viewer"] as Player
                    submitAsync(delay = 20) {
                        GermThemeUI(viewer,it).open()
                    }
                }

            }
            PluginReloadEvent().call()
            sender.sendMessage("reload successful.")
        }

    }
}